package servlet.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;
import dao.AdminDao;
import dao.DepartmentDao;
import dao.UserDao;
import dbutil.DBHelper;
import entity.Admin;
import entity.AdminPrivs;
import entity.Department;
import entity.User;

public class AdminLoginServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7506858589981897642L;

	public AdminLoginServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String adminName = request.getParameter("adminname");
		String password = request.getParameter("md5password");
		AdminDao adminDao = null;
		Admin admin = null;
		AdminPrivs adminPrivs = null;
		Set<String> privsSet = null;
		List<String> list = null;
		
		try {
			adminDao = new AdminDao();
			list = new ArrayList<String>();
			admin = adminDao.getAdminByNP(adminName, password);
			adminPrivs = adminDao.queryAdminPrivs(adminName);
			HttpSession session = request.getSession();

			if (admin != null && "正常".equals(admin.getStatus())) {
				session.setAttribute("admin", admin);
				
				// 用list保存权限
				privsSet = adminPrivs.getPrivNameAddUser().keySet();
				if (privsSet.size() > 0) {
					for(String priv : privsSet) {// 一条记录多个权限
						list.add(priv);
					}
				}
				session.setAttribute("privs", list);
				
				response.sendRedirect(request.getContextPath() + "/views/main.jsp");
			} else {
				session.setAttribute("msg", "账号密码错误或账户不可用，请重新登陆");
				response.sendRedirect(request.getContextPath() + "/login/login.jsp");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void init() throws ServletException {
	}

}
 